﻿namespace PowerSong.UserInterface
    {
    using System.Windows;
    using PowerSong.Import;
    using PowerSong.SongDatabase;
    using PowerSong.UserInterface.Tasks;

    /// <summary>
    /// Interaction logic for ImportWindow.xaml
    /// </summary>
    public partial class ImportWindow : Window
        {

        private bool bbeInstalled = false;

        public ImportWindow()
            {
            InitializeComponent();
            this.bbeInstalled = BibleTranslationManager.IsTranslationInstalled("BBE") || BibleTranslationManager.IsTranslationInstalled("Bible in Basic English");
            ImportModernDatabaseRadioButton.IsChecked = true;
            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            string[] result = null;
            var interimDatabase = Database.Create();
            if (ImportModernDatabaseRadioButton.IsChecked == true)
                {
                
                // Import the data from the specified modern-style database
                result = ImportModernDatabase(interimDatabase, ModernDatabaseFileName.FileName);

                }
            else if (DownloadFromWebsiteRadioButton.IsChecked == true)
                {

                // Download the data from the PowerSong website
                result = ImportFromWebsite(interimDatabase,
                                           DownloadSongsCheckBox.IsChecked == true,
                                           DownloadStylesCheckBox.IsChecked == true,
                                           DownloadBbeCheckBox.IsChecked == true);

                }
            else if (ImportLegacyDatabaseRadioButton.IsChecked == true)
                {

                // Import the data from the given legacy PowerSong database
                result = ImportLegacyDatabase(interimDatabase, LegacyDatabaseLocation.FolderName);

                }
            else if (ImportLegacyExportRadioButton.IsChecked == true)
                {

                // Import the data from the given legacy PowerSong export file
                result = ImportLegacyExportFile(interimDatabase, LegacyExportFileLocation.FileName);

                }
            else if (ImportOpenLyricsRadioButton.IsChecked == true)
                {

                // Import the data from the given OpenLyrics database
                result = ImportOpenLyricsDatabase(interimDatabase, OpenLyricsLocation.FolderName);

                }
            else if (ImportPresenterRadioButton.IsChecked == true)
                {

                // Import the data as it originates from the Presenter software
                result = ImportPresenter(interimDatabase,
                                         PresenterDatabaseLocation.FolderName, 
                                         PresenterRecurseCheckBox.IsChecked == true);

                }

            // Did the import work?
            if (result != null)
                {

                // Show messages
                if (result.Length > 0) MessagesWindow.Show("The following problems are present the data retrieved from the selected database. Please review these messages before continuing.", result);

                // Ask the user which items they wish to import
                var window = new SelectItemsWindow(interimDatabase.Songs.GetAllSongs(),
                                                   interimDatabase.Styles.GetAllStyles());
                if (window.ShowDialog() == true)
                    {

                    // Copy licenses and categories used by the selected songs
#warning Rethink the notion of importing of categories and licenses. I also don't like the below block of code.
                    foreach (var song in window.SelectedSongs)
                        {
                        if (song.License != null)
                            {
                            if (!State.Database.Licenses.Contains(song.License.ID))
                                {
                                State.Database.Licenses.Write(song.License);
                                }
                            song.License = State.Database.Licenses.Get(song.License.ID); // Must update the object reference
                            }
                        for (var categoryIndex = 0; categoryIndex < song.Categories.Count; categoryIndex++)
                            {
                            var category = song.Categories[categoryIndex];
                            if (!State.Database.Categories.Contains(category.ID))
                                {
                                State.Database.Categories.Write(category);
                                }
                            song.Categories[categoryIndex] = State.Database.Categories.Get(category.ID); // Must update the object reference
                            }
                        }

                    // Copy songs from the temporary database into the current database
                    foreach (var song in window.SelectedSongs)
                        {
                        State.Database.Songs.Write(song);
                        }

                    // Copy styles from the temporary database into the current database
                    foreach (var style in window.SelectedStyles)
                        {
                        State.Database.Styles.Write(style);
                        }

                    // Rebuild the song index
                    ProgressWindow.Start(new RecreateIndexTask());

                    // All done!
                    Utilities.ShowInformationMessage("Completed", "The data has been imported. It should now be available.");
                    this.DialogResult = true;

                    }

                }

            }

        private string[] ImportModernDatabase(Database interimDatabase, string fileName)
            {

            // Ensure a location has been specified
            if (string.IsNullOrWhiteSpace(fileName))
                {
                Utilities.ShowErrorMessage("Error", "Please specify the file name of the other PowerSong database to import items from.");
                return null;
                }

            // Go ahead and actually import the data into the interim database
            var importer = new ModernDatabaseImport(interimDatabase, fileName);
            var task = new ImportTask(importer, null, "Retrieving items from the specified PowerSong database...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ImportFromWebsite(Database interimDatabase, bool downloadSongs, bool downloadStyles, bool downloadBbe)
            {

            // Are we doing anything at all?
            if (!downloadSongs && !downloadStyles && !downloadBbe)
                {
                Utilities.ShowErrorMessage("Error", "Please select something to download from the PowerSong website.");
                return null;
                }

            // Go ahead and actually import the data into the interim database
            var importer = new WebsiteImport(interimDatabase, downloadSongs, downloadStyles, downloadBbe);
            var task = new ImportTask(importer, "Downloaded from Website", "Retrieving items from the PowerSong website...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ImportLegacyDatabase(Database interimDatabase, string location)
            {

            // Ensure a location has been specified
            if (string.IsNullOrWhiteSpace(location))
                {
                Utilities.ShowErrorMessage("Error", "Please specify the location of an existing legacy PowerSong database.");
                return null;
                }

            // The location must specify a valid PowerSong 2 database
            if (!PowerSong.SongDatabase.Legacy.Database.IsValidDatabase(location))
                {
                Utilities.ShowErrorMessage("Error", "The specified location does not appear to contain a valid legacy PowerSong database.");
                }

            // Go ahead and actually import the data into the interim database
            var importer = new LegacyDatabaseImport(interimDatabase, location);
            var task = new ImportTask(importer, "Converted from Legacy Database", "Retrieving items from the specified legacy database...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ImportLegacyExportFile(Database interimDatabase, string fileName)
            {

            // Ensure a location has been specified
            if (string.IsNullOrWhiteSpace(fileName))
                {
                Utilities.ShowErrorMessage("Error", "Please specify the file name of an existing legacy PowerSong export file.");
                return null;
                }

            // Go ahead and actually import the data into the interim database
            var importer = new LegacyExportFileImport(interimDatabase, fileName);
            var task = new ImportTask(importer, "Converted from Legacy Export File", "Retrieving items from the legacy PowerSong 1.0 export file...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ImportOpenLyricsDatabase(Database interimDatabase, string sourceFolderLocation)
            {

            // Ensure a location has been specified
            if (string.IsNullOrWhiteSpace(sourceFolderLocation))
                {
                Utilities.ShowErrorMessage("Error", "Please specify the location of the folder containing one or more OpenLyrics files so that they can be converted.");
                return null;
                }

            // Go ahead and actually import the data into the interim database
            var importer = new OpenLyricsImport(interimDatabase, sourceFolderLocation);
            var task = new ImportTask(importer, "Converted from OpenLyrics", "Retrieving items from the specified OpenLyrics database...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ImportPresenter(Database interimDatabase, string sourceFolderLocation, bool includeSubFolders)
            {

            // Ensure a location has been specified
            if (string.IsNullOrWhiteSpace(sourceFolderLocation))
                {
                Utilities.ShowErrorMessage("Error", "Please specify the location of the Presenter data so that it can be converted.");
                return null;
                }

            // Go ahead and actually import the data into the interim database
            var importer = new PresenterImport(interimDatabase, sourceFolderLocation, includeSubFolders);
            var task = new ImportTask(importer, "Converted from Presenter", "Retrieving items from the specified Presenter database...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private void SomethingChecked(object sender, RoutedEventArgs e)
            {
            DownloadSongsCheckBox.IsEnabled = DownloadFromWebsiteRadioButton.IsChecked == true;
            DownloadStylesCheckBox.IsEnabled = DownloadFromWebsiteRadioButton.IsChecked == true;
            DownloadBbeCheckBox.IsEnabled = DownloadFromWebsiteRadioButton.IsChecked == true && !bbeInstalled;
            LegacyDatabaseLocation.IsEnabled = ImportLegacyDatabaseRadioButton.IsChecked == true;
            LegacyExportFileLocation.IsEnabled = ImportLegacyExportRadioButton.IsChecked == true;
            OpenLyricsLocation.IsEnabled = ImportOpenLyricsRadioButton.IsChecked == true;
            PresenterDatabaseLocation.IsEnabled = ImportPresenterRadioButton.IsChecked == true;
            PresenterRecurseCheckBox.IsEnabled = ImportPresenterRadioButton.IsChecked == true;
            ModernDatabaseFileName.IsEnabled = ImportModernDatabaseRadioButton.IsChecked == true;
            }

        }

    }
